#include "tabbar.h"

#include "lualib.h"
#include "lua.h"
#include "lauxlib.h"

#include <string.h>
#include <stdio.h>
#include <memory.h>
#include <stdlib.h>

extern lua_State* g_ufo_lua_state;

static int lua_ufoTabBarSetSelectedItem(lua_State *L)
{
	UFO_View view = *(UFO_View*)luaL_checkudata(L, 1, "ufo.ufoView");
    int nItem = lua_tonumber(L, 2);
    
    lua_pushinteger(L, ufoTabBarSetSelectedItem(view, nItem));
    
	return 1;
}

static int lua_ufoTabBarGetSelectedItem(lua_State *L)
{
	UFO_View view = *(UFO_View*)luaL_checkudata(L, 1, "ufo.ufoView");
    
    lua_pushinteger(L, ufoTabBarGetSelectedItem(view));
    
	return 1;
}

static int lua_ufoTabBarSetSelImage(lua_State *L)
{
	UFO_View view = *(UFO_View*)luaL_checkudata(L, 1, "ufo.ufoView");
    
    int nItem = lua_tonumber(L, 2);
    const char *image = lua_tostring(L, 3);
	UFO_Texture tex = ufoResourceGetTexture(image);
    
    lua_pushinteger(L, ufoTabBarSetSelImage(view, nItem, tex));
    
	return 1;
}

static int lua_ufoTabBarSetUnSelImage(lua_State *L)
{
	UFO_View view = *(UFO_View*)luaL_checkudata(L, 1, "ufo.ufoView");
    
    int nItem = lua_tonumber(L, 2);
    const char *image = lua_tostring(L, 3);
	UFO_Texture tex = ufoResourceGetTexture(image);
    
    lua_pushinteger(L, ufoTabBarSetUnSelImage(view, nItem, tex));
    
	return 1;
}

static const struct luaL_Reg tabviewlib [] = {
	{"setSelectedItem", lua_ufoTabBarSetSelectedItem},
	{"setSelImage", lua_ufoTabBarSetSelImage},
	{"setUnSelImage", lua_ufoTabBarSetUnSelImage},
   	{"getSelectedItem", lua_ufoTabBarGetSelectedItem},
	{0, 0},
};

int internal_initializationScript_tabbar()
{
	if (!g_ufo_lua_state) {
		g_ufo_lua_state = luaL_newstate();
		luaL_openlibs(g_ufo_lua_state);
	}

	luaL_newmetatable(g_ufo_lua_state, "ufo.ufoView");

	lua_pushvalue(g_ufo_lua_state, -1);
	lua_setfield(g_ufo_lua_state, -2, "__index");

	luaL_register(g_ufo_lua_state, 0, tabviewlib);

	return 1;
}